package com.example.myapplication;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class ConfirmReceiptActivity extends AppCompatActivity {

    private EditText etRecipientName, etPhoneNumber, etAddress;
    private Button btnConfirmReceipt;
    private DBHelper dbHelper;
    private int transactionId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_receipt);

        // 初始化组件
        etRecipientName = findViewById(R.id.etRecipientName);
        etPhoneNumber = findViewById(R.id.etPhoneNumber);
        etAddress = findViewById(R.id.etAddress);
        btnConfirmReceipt = findViewById(R.id.btnConfirmReceipt);
        // 获取并设置订单信息
        TextView tvOrderInfo = findViewById(R.id.tvOrderInfo);
        // 随机生成订单编号

        String orderInfo = "订单编号：" + (int) (Math.random() * 1000000)   + "\n" +
                "商品名称：" + getIntent().getStringExtra("product_name") + "\n" +
                "购买日期：" + getIntent().getStringExtra("purchase_date");
        tvOrderInfo.setText(orderInfo);

        dbHelper = new DBHelper(this);

        // 获取传递的交易ID
        transactionId = getIntent().getIntExtra("transaction_id", -1);

        // 确认收货按钮点击事件
        btnConfirmReceipt.setOnClickListener(v -> {
            // 获取输入的收货信息
            String name = etRecipientName.getText().toString().trim();
            String phone = etPhoneNumber.getText().toString().trim();
            String address = etAddress.getText().toString().trim();

            if (name.isEmpty() || phone.isEmpty() || address.isEmpty()) {
                Toast.makeText(this, "请填写完整的收货信息", Toast.LENGTH_SHORT).show();
                return;
            }

            // 弹出确认对话框
            new AlertDialog.Builder(this)
                    .setTitle("确认收货")
                    .setMessage("是否确认已收货？")
                    .setPositiveButton("确认", (dialog, which) -> {
                        // 更新交易状态为“已收货”
                        updateTransactionStatus("已收货");
                        Toast.makeText(this, "收货成功，感谢您的购买！", Toast.LENGTH_SHORT).show();
                        finish();
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }

    // 更新交易状态的方法
    private void updateTransactionStatus(String status) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("status", status);
        db.update("transactions", values, "transaction_id = ?", new String[]{String.valueOf(transactionId)});
        db.close();
    }
}
